<?php

namespace App\Http\Controllers\Auth;

use App\Http\Model\Auth;
use Cartalyst\Sentry\Facades\Laravel\Sentry;
use Illuminate\Http\Request;
use App\Http\Requests;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Validator;

class AuthController extends CommonController
{
    //用户界面
    public function user(){
        //$users = Sentry::findAllUsers();
        //dd($users);
        //$users->paginate(1);
        $users=DB::table('users')->paginate(8);
        foreach($users as $v){
            $user = Sentry::findUserByID($v->id);
            //$guser=DB::table('users_groups')->where('user_id',)->first();
            $v->group=$user->getGroups();
        }
        $page=page_nav($users);
        return view('admin.user.user',['data'=>$users,'page'=>$page]);
    }
    //创建用户
    public function createUser(){
        if($input=Input::all()){
            $rules=[
                'email'=>'required|email',
                'password'=>'between:6,20',
            ];
            $message=[
                'password.between'=>'新密码范围必须在6-20位之间！',
                'email.required' => '必须填写登录邮箱',
                'email.email' => '请填写正确的邮箱',
            ];
            $validator=Validator::make($input,$rules,$message);
            if(!$validator->passes()){
                return back()->withErrors($validator);
            }
            try
            {
                $input = Input::except('_token');
                $user = Sentry::createUser(array(
                    'email'     => $input['email'],
                    'password'  => $input['password'],
                    'nickname'  => $input['nickname'],
                    'activated' => true,
                ));
                // 查找用户组 where 为 组id ＝ 1
                $adminGroup = Sentry::findGroupById($input['g_id']);
                // 把 用户加到 用户组
                $user->addGroup($adminGroup);
                return back()->with('errors','添加用户成功!');
            }
            catch (\Cartalyst\Sentry\Users\LoginRequiredException $e)
            {
                return back()->with('errors','登录帐号(邮箱不存在)!');
            }
            catch (\Cartalyst\Sentry\Users\PasswordRequiredException $e)
            {
                return back()->with('errors','没有提供密码,请稍后重试!');
            }
            catch (\Cartalyst\Sentry\Users\UserExistsException $e)
            {
                return back()->with('errors','用户已经存在,请稍后重试!');
            }
            catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e)
            {
                return back()->with('errors','用户不存在,请稍后重试!');
            }
        }else{
            $groups = Sentry::findAllGroups();
            return view('admin.user.userAdd',['group'=>$groups]);
        }
    }
    //修改用户
    public function editUser(){
        if($input=Input::all()){
            $rules=[
                'password'=>'between:6,20|confirmed',
            ];
            $message=[
                'password.between'=>'新密码范围必须在6-20位之间！',
                'password.confirmed'=>'新密码和确认密码不一致！',
            ];
            try
            {
                // 通过 分组ID 查找分组
                $user = Sentry::findUserById($input['id']);
                // 更新分组详情
                $adminGroup = Sentry::findGroupById($input['g_id']);
                if (!$user->addGroup($adminGroup)){
                    return back()->with('errors','用户组绑定失败,请重试!');
                }else{
                    DB::table('users_groups')->where('user_id',$input['id'])->where('group_id','!=',$input['g_id'])->delete();
                }
                $user->nickname = $input['nickname'];

                if($input['password']){
                    $validator=Validator::make($input,$rules,$message);

                    if(!$validator->passes()){
                        return back()->withErrors($validator);
                    }
                    $user->password = $input['password'];
                }
                // 更新分组
                if ($user->save())
                {
                    return back()->with('errors','用户修改成功!');
                }else{
                    return back()->with('errors','用户修改失败,请重试!');
                }
            }
            catch (\Cartalyst\Sentry\Users\UserExistsException $ee) {
                return back()->with('errors','用户登录邮箱必须存在,请重试!');
            }
            catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
                return back()->with('errors','用户不存在,请重试!');
            }
        }else{
            $user=Sentry::findUserById(Route::input('id'));
            if(count($user->getGroups())>0){
                $group = $user->getGroups()[0];
            }else{
                $group = array();
            }
            $groups = Sentry::findAllGroups();
            return view('admin.user.userEdit',['groups'=>$groups,'group'=>$group,'user'=>$user]);
        }
    }
    //删除用户
    public function delUser(){
        $input=Input::all();
        if(!isset($input['ids'])){
            try {
                $id = Route::input('id');
                // 通过 分组ID 查找分组
                $user  = Sentry::findUserById($id);

                // 删除分组
                if ($user ->delete()) {
                    $data = [
                        'status' => 200,
                        'msg' => '用户删除成功！',
                    ];
                } else {
                    $data = [
                        'status' => 300,
                        'msg' => '用户删除失败，请稍后重试！',
                    ];
                }
            } catch (\Cartalyst\Sentry\Users\UserNotFoundException $e) {
                $data = [
                    'status' => 300,
                    'msg' => '用户不存在，请稍后重试！',
                ];
            }
        }else{
            $ids = explode(",", $input['ids']);
            foreach($ids as $v){
                if($v){
                    Sentry::findUserById($v)->delete();
                }
            }
            $data = [
                'status' => 200,
                'msg' => '权限删除成功！',
            ];
        }
        return $data;
    }



    //用户组界面
    public function group(){
        //$groups = Sentry::findAllGroups();
        $groups=DB::table('groups')->paginate(8);
        $page=page_nav($groups);
        return view('admin.user.group',['groups'=>$groups,'page'=>$page]);
    }

    //创建用户组界面
    public function createGroup(){
        if($input=Input::all()){
            try
            {
                // 创建分组
                $group = Sentry::createGroup(array(
                    'name'=> $input['name'],
                    'permissions' =>json_decode($input['permission'],true),
                ));
                $data = [
                    'status' => 200,
                    'msg' => '添加分组成功!',
                ];
            }

            catch (\Cartalyst\Sentry\Groups\NameRequiredException $e){
                $data = [
                    'status' => 200,
                    'msg' => '分组名称必须存在!',
                ];
            }
            catch (\Cartalyst\Sentry\Groups\GroupExistsException $e){
                $data = [
                    'status' => 200,
                    'msg' => '分组已经存在!',
                ];
            }
            return $data;
        }else{
            $roles=Auth::select('id', 'name','role','a_id as pId')->get();
            $data=catzTree($roles,'a_id',array(),true);
            return view('admin.user.groupAdd',['role'=>$data]);
        }
    }

    //修改用户组界面
    public function editGroup(){
        if($input=Input::all()){
            try
            {
                // 通过 分组ID 查找分组
                $group = Sentry::findGroupById($input['id']);
                $newArr=array();
                foreach ($group->permissions as $key => $value) {
                    $newArr[$key]=0;
                }
                $group->permissions=$newArr;
                $group->save();
                // 更新分组详情
                $group->name = $input['name'];
                $group->permissions =json_decode($input['permission'],true);
                // 更新分组
                if ($group->save())
                {
                    $data = [
                        'status' => 200,
                        'msg' => '分组配置/修改成功',
                    ];
                }else{
                    $data = [
                        'status' => 300,
                        'msg' => '分组配置/修改失败,请重试!',
                    ];
                }
            }
            catch (\Cartalyst\Sentry\Groups\NameRequiredException $e) {
                $data = [
                    'status' => 300,
                    'msg' => '分组名称必须存在,请重试!',
                ];
            }
            catch (\Cartalyst\Sentry\Groups\GroupExistsException $e) {
                $data = [
                    'status' => 300,
                    'msg' => '分组已经存在,请重试!',
                ];
            }
            catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
                $data = [
                    'status' => 300,
                    'msg' => '分组不存在,请重试!',
                ];
            }
            return $data;
        }else{
            $group = Sentry::findGroupById(Route::input('id'));
            $groupPermissions = $group->getPermissions();
            $roles=Auth::select('id', 'name','role','a_id as pId')->get();
            $data=catzTree($roles,'a_id',$groupPermissions,true);
            return view('admin.user.groupEdit',['group'=>$group,'role'=>$data]);
        }
    }

    //删除用户组
    public function delGroup(){
        $input=Input::all();
        if(!isset($input['ids'])){
            try {
                $id = Route::input('id');
                // 通过 分组ID 查找分组
                $group = Sentry::findGroupById($id);

                // 删除分组
                if ($group->delete()) {
                    $data = [
                        'status' => 200,
                        'msg' => '用户组删除成功！',
                    ];
                } else {
                    $data = [
                        'status' => 300,
                        'msg' => '用户组删除失败，请稍后重试！',
                    ];
                }
            } catch (\Cartalyst\Sentry\Groups\GroupNotFoundException $e) {
                $data = [
                    'status' => 300,
                    'msg' => '用户组不存在，请稍后重试！',
                ];
            }
        }else{
            $ids = explode(",", $input['ids']);
            foreach($ids as $v){
                if($v){
                    Sentry::findGroupById($v)->delete();
                }
            }
            $data = [
                'status' => 200,
                'msg' => '权限删除成功！',
            ];
        }
        return $data;
    }



    //权限路径列表
    public function role(){
        $auth=Auth::get();
        //$auth=DB::table('auths')->paginate(8);
        $data=catlist($auth,'a_id','_cate_name');
        return view('admin.user.role')->with('data',$data);
    }

    //添加role
    public function createRole(){
        if($input=Input::all()){
            $input = Input::except('_token');
            $auth=Auth::where('name',$input['name'])->first();
            if(!$auth){
                //$input['created_at']=date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
                //$input['updated_at']=date('Y-m-d H:i:s',$_SERVER['REQUEST_TIME']);
                if(!$input['name'] || !$input['role']){
                    return back()->with('errors','权限名称和详细不能为空!');
                }
                if(Auth::insertGetId($input)){
                    return back()->with('errors','权限添加成功!');
                }else{
                    return back()->with('errors','权限添加失败!');
                }
            }else{
                return back()->with('errors','权限名称已经存在!');
            }
        }else{
            $auth=Auth::get();
            $data=catlist($auth,'a_id','_cate_name');
            return view('admin.user.roleAdd')->with('data',$data);
        }
    }

    //添加role
    public function editRole(){
        if($input=Input::all()){
            $input = Input::except('_token');
            $auth = Auth::where('id',$input['id'])->first();
            if(!$input['name'] || !$input['role']){
                return back()->with('errors','权限名称和详细不能为空!');
            }
            if($auth){
                if(Auth::where('id',$input['id'])->update($input)){
                    return back()->with('errors','权限修改成功!');
                }else{
                    return back()->with('errors','权限修改失败!');
                }
            }else{
                return back()->with('errors','权限不存在,请重试!');
            }
        }else{
            $auth=Auth::get();
            $data=catlist($auth,'a_id','_cate_name');
            $role = Auth::where('id',Route::input('id'))->first();
            $ids=getChildsId($auth,Route::input('id'));
            foreach($data as $v){
                if(in_array($v->id,$ids) || $v->id==Route::input('id')){
                    $v['disabled']=1;
                }else{
                    $v['disabled']=0;
                }
            }
            return view('admin.user.roleEdit',['data'=>$data,'role'=>$role]);
        }
    }

    //删除权限
    public function delRole(){
        $input=Input::all();
        if(!isset($input['ids'])){
            $auth = Auth::where('id',Route::input('id'))->first();
            if($auth) {
                // 删除分组
                if (Auth::where('id',Route::input('id'))->delete()) {
                    $data = [
                        'status' => 200,
                        'msg' => '权限删除成功！',
                    ];
                } else {
                    $data = [
                        'status' => 300,
                        'msg' => '权限删除失败，请稍后重试！',
                    ];
                }
            }else{
                $data = [
                    'status' => 300,
                    'msg' => '权限不存在，请稍后重试！',
                ];
            }
        }else{
            $ids = explode(",",$input['ids']);
            foreach($ids as $v){
                Auth::where('id',$v)->delete();
            }
            $data = [
                'status' => 200,
                'msg' => '权限删除成功！',
            ];
        }
        return $data;
    }
}
